<?php
/**
 * Author: Traveler
 * Time  : 2021/10/15 12:07
 */

namespace app\controller\crm\v1;


use app\ErrorCode;
use app\service\IcafeCnkService;
use sunshine\basic\BaseController;
use sunshine\exceptions\ApiException;
use think\App;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\exception\ValidateException;
use think\Response;

class IcafeCnk extends BaseController
{
    /**
     * IcafeCnk constructor.
     *
     * @param App             $app
     * @param IcafeCnkService $service
     */
    public function __construct(App $app, IcafeCnkService $service)
    {
        parent::__construct($app);
        $this->service = $service;
    }

    /**
     * 获取净网先锋信息
     *
     * @return Response
     */
    public function get(): Response
    {
        $icafe_id = $this->request->get('icafe_id');
        if (!$icafe_id) {
            throw new ApiException(ErrorCode::MISSING_PARAMETERS);
        }

        $data = $this->service->getCnk($icafe_id);

        return $this->json->api(ErrorCode::SUCCESS, $data);
    }

    /**
     * 保存净网先锋信息
     *
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function save(): Response
    {
        $icafe_id = $this->request->put('icafe_id');
        if (!$icafe_id) {
            throw new ApiException(ErrorCode::MISSING_PARAMETERS);
        }

        $data = $this->request->put();

        try {
            $this->validate($data, 'IcafeTechValidate.cnk');
        } catch (ValidateException $e) {
            throw new ApiException(is_string($e->getError()) ? ErrorCode::UNKNOWN_VALIDATE_MSG : $e->getError());
        }

        if (!$this->service->saveCnk($icafe_id, $data)) {
            throw new ApiException(ErrorCode::SAVE_FAILED);
        }

        return $this->json->api(ErrorCode::SUCCESS);
    }
}